package i.i.myapplication.view;

//package i.i.myapplication.view;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MusicService extends Service {

    private static final String TAG = "MusicService";

    private MediaPlayer player;
    private MusicControl musicControl;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        if (musicControl == null) {
            musicControl = new MusicControl();
        }
        return musicControl;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
    }

    public class MusicControl extends Binder {

        // 播放指定音乐资源，传入的 i 是序号，比如 music1, music2...
        public void play(int i) {
            try {
                // 先重置播放器
                player.reset();

                // 这里假设你的资源文件命名为 music1.mp3, music2.mp3 ... 放在 res/raw 目录
                int resId = getResources().getIdentifier("music" + i, "raw", getPackageName());

                if (resId == 0) {
                    Log.e(TAG, "Music resource not found for: music" + i);
                    return;
                }

                // 创建播放器，加载资源
                player = MediaPlayer.create(getApplicationContext(), resId);
                if (player == null) {
                    Log.e(TAG, "MediaPlayer.create returned null");
                    return;
                }

                player.start();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 添加获取当前播放位置的方法
        public int getCurrentPosition() {
            if (player != null) {
                return player.getCurrentPosition();
            }
            return 0;
        }

        // 同理你也需要补充 getDuration 方法
        public int getDuration() {
            if (player != null) {
                return player.getDuration();
            }
            return 0;
        }
        // 暂停播放
        public void pausePlay() {
            if (player != null && player.isPlaying()) {
                player.pause();
            }
        }

        // 继续播放
        public void continuePlay() {
            if (player != null && !player.isPlaying()) {
                player.start();
            }
        }

        // 跳转播放进度
        public void seekTo(int progress) {
            if (player != null) {
                player.seekTo(progress);
            }
        }

        // 是否正在播放
        public boolean isPlaying() {
            return player != null && player.isPlaying();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player != null) {
            if (player.isPlaying()) {
                player.stop();
            }
            player.release();
            player = null;
        }
    }
}
